<template>
  <div class="page">
    <div class="c-main p20">
      <div class="c-body">
        <el-row type="flex" justify="left">
          <el-col :span="20" :offset="2">
            <el-form ref="form" :model="pageAjax.data" label-width="120px">
              <el-form-item label="公司名称：">
                <el-input
                  placeholder="请输入公司名称"
                  v-model="pageAjax.data.name"
                ></el-input>
              </el-form-item>
              <el-form-item label="公司状态：">
                <el-radio-group v-model="pageAjax.data.status" size="medium">
                  <el-radio border :label="0">正常</el-radio>
                  <el-radio border :label="1">已禁用</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="公司后缀：">
                <el-input
                  placeholder="请输入公司后缀，如yj543.com"
                  v-model="pageAjax.data.accountSuffix"
                ></el-input>
              </el-form-item>
              <div class="c-functions">
                <el-tabs v-model="functionTabCp.data.current">
                  <el-tab-pane label="功能" name="function">
                    <div class="c-head clearfix">
                      请选择公司的功能权限
                      <div class="fr mr20">
                        <el-checkbox
                          v-model="alone.checkAllFn"
                          @change="rCheckAllFn"
                          >全选</el-checkbox
                        >
                      </div>
                    </div>
                    <div class="c-body">
                      <el-tree
                        show-checkbox
                        node-key="id"
                        ref="fnTreeCpRef"
                        :data="functionSupAjax.data"
                        :default-checked-keys="alone.checkedFn"
                        :props="fnTreeCp.config.defaultProps"
                        :check-strictly="fnTreeCp.config.checkStrictly"
                      >
                      </el-tree>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
              <el-divider></el-divider>
              <div class="c-account">
                <div class="c-accountBtn">
                  <el-button
                    type="default"
                    icon="el-icon-circle-plus-outline"
                    @click="rAddAccount"
                    >新增管理员账号</el-button
                  >
                </div>

                <div class="c-accountList">
                  <div
                    class="c-accountItem"
                    :key="index"
                    v-for="(item, index) in pageAjax.data.adminAccountVos"
                  >
                    <div class="c-accountTitle">
                      <span>管理员账号{{ index + 1 }}</span>
                      <i
                        class="el-icon-delete"
                        @click="rDeleteAccount(index)"
                      ></i>
                    </div>
                    <div class="c-accountForm">
                      <el-form-item label="登陆账号：">
                        <el-input
                          placeholder="请输入登陆账号"
                          :disabled="
                            !!pageAjax.data.adminAccountVos[index].userId
                          "
                          v-model="
                            pageAjax.data.adminAccountVos[index].loginAccount
                          "
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="登陆密码：">
                        <el-input
                          placeholder="请输入登陆密码"
                          v-model="
                            pageAjax.data.adminAccountVos[index].password
                          "
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="再次输入密码：">
                        <el-input
                          placeholder="请再次输入密码"
                          v-model="
                            pageAjax.data.adminAccountVos[index].confirmPassword
                          "
                        ></el-input>
                      </el-form-item>
                    </div>
                  </div>
                </div>
              </div>
              <el-form-item class="mt20">
                <el-button type="primary" @click="rSubmitForm">提交</el-button>
                <el-button @click="rBack">取消</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script>
import { getOffspringnTree } from "@/assets/js/util.js";
import {
  addCorporation,
  getFunctionList,
  getCorporationDetail
} from "@/api/authority.js";
import _ from "lodash";

export default {
  name: "system_authorityEditCorporation",
  data: () => ({
    pageAjax: {
      btnDisabled: false,
      btnLoading: false,
      loading: false,
      data: {
        name: "", // 公司名称
        status: 0, // 状态
        accountSuffix: "", //公司后缀
        funcIds: [], // 功能节点
        adminAccountVos: []
      }
    },
    corporationSupAjax: {
      data: []
    },
    // 全部功能节点
    functionSupAjax: {
      data: []
    },
    alone: {
      checkAllFn: false,
      checkedFn: []
    },

    fnTreeCp: {
      config: {
        defaultProps: {
          children: "children",
          label: "name"
        },
        checkStrictly: false
      }
    },
    // 功能列表tab配置
    functionTabCp: {
      config: {},
      data: {
        current: "function"
      }
    }
  }),
  created() {
    let _that = this;
    _that.getFunctionListData().then(() => {
      _that.getPageData();
    });
  },
  methods: {
    rAddAccount() {
      let _that = this;
      let obj = {
        confirmPassword: "",
        loginAccount: "",
        password: ""
      };
      if (!_that.pageAjax.data.adminAccountVos) {
        _that.pageAjax.data.adminAccountVos = [];
      }
      if (_that.pageAjax.data.adminAccountVos.length > 2) {
        _that.$message.error("管理员账号最多只能3个");
        return;
      }
      _that.pageAjax.data.adminAccountVos.push(obj);
    },
    rDeleteAccount(index) {
      let _that = this;
      _that
        .$confirm("你确定要删除此管理员账号?", "删除提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          _that.pageAjax.data.adminAccountVos.splice(index, 1);
        });
    },
    rSubmitForm() {
      let _that = this;
      let formData = _.cloneDeep(_that.pageAjax.data);

      if (!formData.name) {
        _that.$message.error("公司名称不能为空");
        return;
      }

      if (!/^\w+(\.\w+){1,2}$/.test(formData.accountSuffix)) {
        _that.$message.error("公司后缀有问题，必须以类似yj543.com域名方式");
        return;
      }
      //let loadingHand = _that.$loading();

      let checkedKeys = _that.$refs.fnTreeCpRef.getCheckedKeys();
      // let checkedKeys;
      // let fullCheckedKey = _that.$refs.fnTreeCpRef.getCheckedKeys();
      // let halfCheckedKeys = _that.$refs.fnTreeCpRef.getHalfCheckedKeys();
      // checkedKeys = halfCheckedKeys.concat(fullCheckedKey);

      if (!checkedKeys.length) {
        _that.$message.error("公司权限不能为空");
        return;
      }
      formData.funcIds = checkedKeys;
      formData.adminAccountVos = formData.adminAccountVos
        ? formData.adminAccountVos
        : [];
      let accountLen = formData.adminAccountVos.length;
      if (!formData.adminAccountVos.length) {
        _that.$message.error("公司管理员账号不能为空");
        return;
      }
      for (let i = 0; i < accountLen; i++) {
        if (!formData.adminAccountVos[i].loginAccount) {
          _that.$message.error("公司管理员账号" + (i + 1) + "不能为空");
          return;
        }

        if (
          !formData.adminAccountVos[i].userId &&
          (!formData.adminAccountVos[i].password ||
            !formData.adminAccountVos[i].confirmPassword)
        ) {
          _that.$message.error(
            "公司管理员账号" + (i + 1) + "的密码或确认密码不能为空"
          );
          return;
        }
        if (formData.adminAccountVos[i].userId) {
          // 修改
          if (
            formData.adminAccountVos[i].password &&
            formData.adminAccountVos[i].password.length < 6
          ) {
            _that.$message.error(
              "公司管理员账号" + (i + 1) + "的密码位数必须大于5"
            );
            return;
          }
        } else {
          if (formData.adminAccountVos[i].password.length < 6) {
            _that.$message.error(
              "公司管理员账号" + (i + 1) + "的密码位数必须大于5"
            );
            return;
          }
        }
        if (
          formData.adminAccountVos[i].password !==
          formData.adminAccountVos[i].confirmPassword
        ) {
          _that.$message.error(
            "公司管理员账号" + (i + 1) + "的密码和确认密码不相等"
          );
          return;
        }
      }
      if (_that.pageAjax.loading) {
        return;
      }

      _that.pageAjax.loading = true;
      addCorporation(formData)
        .then(resp => {
          let respData = resp.data || {};
          if (respData.code === _that.STATUS.success[0]) {
            _that.$message({
              type: "success",
              message: "添加成功",
              onClose: () => {
                _that.goRefresh(-1);
              },
              duration: 1200
            });
          } else {
            _that.$message.error(respData.msg || "添加失败");
          }
        })
        .finally(() => {
          _that.pageAjax.loading = false;
        });
    },

    // 功能全选
    rCheckAllFn(val) {
      let _that = this;
      let data = _that.functionSupAjax.data;
      let arr = [];
      if (val) {
        for (var i = data.length; i--; ) {
          arr.push(data[i].id);
        }
      }
      _that.$refs.fnTreeCpRef.setCheckedNodes(arr);
      _that.alone.checkedFn = arr;
    },
    getPageData() {
      let _that = this;
      getCorporationDetail({
        params: { id: _that.$route.query.id }
      })
        .then(resp => {
          let respData = resp.data || {};

          if (respData.code === _that.STATUS.success[0]) {
            _that.pageAjax.data = respData.data;
            let arr = respData.data.funcIds || [];
            // _that.$refs.fnTreeCpRef.setCheckedKeys(arr);
            _that.alone.checkedFn = arr;
            // setTimeout(() => {
            //   _that.fnTreeCp.config.checkStrictly = false;
            // }, 600);
            if (
              respData.data.funcIds.length >=
              _that.functionSupAjax.orginData.length
            ) {
              _that.alone.checkAllFn = true;
            }
          } else {
            _that.$message.error(respData.msg || "获取失败");
          }
        })
        .finally(() => {});
    },
    getFunctionListData() {
      let _that = this;
      return getFunctionList().then(resp => {
        let respData = resp.data;

        if (respData.code === _that.STATUS.success[0]) {
          let arrFunction = respData.data;

          _that.functionSupAjax.orginData = arrFunction;
          _that.functionSupAjax.data = getOffspringnTree(
            _.cloneDeep(arrFunction),
            0
          );
        }
      });
    },
    rBack() {
      this.goRefresh(-1);
    }
  }
};
</script>
<style lang="scss" scoped>
.page {
  .c-account {
    margin-top: 10px;
  }
  .c-accountItem {
    margin-top: 20px;
    border-top: 1px solid #eee;
  }
  .c-accountTitle {
    line-height: 45px;
    font-size: 18px;
    .el-icon-delete {
      margin-left: 10px;
      font-size: 20px;
      color: #f56c6c;
    }
  }
  .s-search {
    border-bottom: 1px solid #eee;
  }
  .c-main {
    margin-top: 20px;
  }
  .c-pagination {
    margin-top: 20px;
    text-align: center;
  }
}
</style>
